// TODO: CODE REVIEW & CLEANUP!
//
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace HomeUX.MusicServer
{

partial class WindowsService : ServiceBase
{
    // We have a separate thread to run AppForm for two reasons:
    // 1. It needs to be in a single-threaded apartment.
    // 2. On startup, the music library is enumerated, and it's possible that could take longer
    //    than the startup timeout period that the Service Control Manager allows - having a
    //    separate thread means OnStart will return quickly, which will make the SCM happier.
    //
    Thread _appFormThread;
    AppForm _appForm;

    public WindowsService()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        _appFormThread = new Thread(AppFormThreadImplementation);
        _appFormThread.SetApartmentState(ApartmentState.STA);
        _appFormThread.Start();
    }

    void AppFormThreadImplementation()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        _appForm = new AppForm();
        Application.Run(_appForm);
    }

    protected override void OnStop()
    {
        _appForm.BeginInvoke((Action)delegate
        {
            _appForm.ExitApplication();
        });
    }
}

}
